$NG.AllReady(function (
	page,
	{
		useDataIndexChange,
		useUpdateRow,
		useUpdateRows,
		useValuesChange,
		useBeforeClick,
		useClick,
	}
) {
	const userInfo = $NG.getUser();
	const mstform = $NG.getCmpApi("p_form_procurement_spare_m");
	const grid1 = $NG.getCmpApi("p_form_procurement_spare_d");
	const toolbar_dgrid1 = $NG.getCmpApi("toolbar_p_form_procurement_spare_d");
	if (toolbar_dgrid1) {
		toolbar_dgrid1.insert({
			id: "chooseWl",
			text: "选择物料",
			iconCls: "icon-New",
		});
	}

	// mstform.setHidden("u_phidkey",false); //设置隐藏
	const getItemValue = (itemName) => mstform.getItem(itemName).getValue();
	/**
	 *@default: 初始化
	 */
	if ($NG.getCmpApi("p_form_procurement_spare_m")) {
		getPtInfoByPhid();
		$NG.updateState((updater) => {
			updater.data.p_form_procurement_spare_m.setProps({
				phid_fcur: {
					value: 1,
					label: "人民币",
				},
				exchangerate: 1,
			});
		});

		if (page.oType == "add") {
			let generateKeyStr = generateKey().toString().replace(".", "");
			mstform.getItem("u_phidkey").setValue(generateKeyStr);
			$NG.execServer("GETuserdept", { phid: userInfo.userID }, (res) => {
				const datas = JSON.parse(res.data)[0].extendObjects;
				console.log(userInfo.userID, "userInfo.userID");

				console.log(datas, "GETuserdeptdatas");
				$NG.updateState((updater) => {
					updater.data.p_form_procurement_spare_m.setProps({
						u_applicant: {
							value: datas.hrid,
							label: datas.username,
						},
						creator: {
							value: datas.hrid,
							label: datas.username,
						},
						u_apply_dept: {
							value: datas.dept_id,
							label: datas.deptname,
						},
						phid_org: {
							value: '',
							label:'',
						},
					});
				});
			});
		}
	}
	/**
	 *@license: 	 //表头字段变化逻辑END	//表头字段变化逻辑BEGIN
	 */
	useValuesChange(async ({ args }) => {
		getPtInfoByPhid();
		setBillName()
		// let _arr = grid1.getRows();
		// let _json = [];
		// let lock = true;
		// setTimeout(async () => {
		// 	_arr.forEach((item) => {
		// 		console.log(`item`, item);
		// 		if (item.u_cost_pc) {
		// 			_json.push({
		// 				u_entity: "WKSSXMZZ",
		// 				u_account: item.u_cost_pc_EXName,
		// 				phid_fcur: mstform.getItem("phid_fcur").getValue(),
		// 			});
		// 		}
		// 	});
		// 	if (
		// 		_json.length == 0 ||
		// 		!mstform.getItem("u_budget_org_no").getValue() ||
		// 		!mstform.getItem("phid_fcur").getValue()
		// 	) {
		// 		lock = false;
		// 	}
		// 	const _data = {
		// 		billType: "WKSD",
		// 		phid_pc: mstform.getItem("phid_pc").getValue(),
		// 		bill_dt: mstform.getItem("bill_dt").getValue(),
		// 		detail: _json,
		// 	};
		// 	//  请求得到的数据
		// 	if (lock) {
		// 		await reqAmt(_data);
		// 		const _datas = resBody.data;
		// 		_datas.forEach((it) => {
		// 			_arr.forEach((item) => {
		// 				if (item.u_cost_pc_EXName == it.account) {
		// 					//TODO 在请求数据中查找并找到相应的数据进行对字段赋值
		// 					item.u_balance = it.balance;
		// 				}
		// 			});
		// 		});
		// 		
		// 	}
		// }, 300);
		grid1.refreshView();
	}, "p_form_procurement_spare_m.phid_pc");
	useClick(async function ({ args }) {
		//按钮点击事件
		$NG.external.openNGHelp({
			type: "NGMultipleHelp",
			helpId: "bpbj_wl",
			valueField: "itemno",
			labelField: "itemno",
			// clientSqlFilter:
			// 	"ng_phid_cu = " + org + " and user_ssbk=" + 787231124000001,
		}).then((data) => {
			console.log(data)
			//data:拿到帮助选中的数据
			var gridArr = []; //定义表体数组
			var gridCount = data.length; //增加的行数,可根据从数据库从取出的数据总数增行
			for (var i = 0; i < gridCount; i++) {
				var gridObj = {
				};
				//对表体字段进行赋值,可以取数据库中的值进行赋值
				gridObj.itemid = data[i].origin.phid;
				gridObj.itemid_EXName = data[i].origin.itemname;
				gridObj.itemno = data[i].origin.itemno;
				gridArr.push(gridObj);
			}
			console.log(gridArr);
			
			grid1.addRows(gridArr);
			grid1.refreshView();
		})
	}, "chooseWl");
	setInterval(() => {
		
		$NG.updateUI((updater) => {
			  // $NG.getPageUI();
			  // 根据组件目录设置路径，可能存在
			  // fieldSetForm
			  // PCFieldSetPanelGroup[i][field]
			  updater.form.p_form_procurement_spare_m.phid_pc.setProps({
				// hidden: true, //隐藏
				// required: true, //必输
				// disabled: true, //只            
				clientSqlFilter: `user_ywlx = 8570000000000353`, //过滤条件
			   
				// placeholder: "请选择", //输入框字段加提示语
				// data: [{ value: "01", label: "实施外包用工" }], //下拉过滤
			  });
		
		  });
	}, 500);
	setBillName()
	function setBillName() {
		$NG.updateState((updater) => {
			updater.data.p_form_procurement_spare_m.setProps({
				bill_name: `${mstform.getItem("phid_pc").getText() == "undefined" ? mstform.getItem("phid_pc").getText() : ""} 备品备件采购申请`
			});
		});
	}

	/**
	 *@function:带出项目信息
	 */
	function getPtInfoByPhid() {
		if (mstform.getItem("phid_pc").getValue()) {
			$NG.execServer(
				"getPtInfoByPhid",
				{ phid: mstform.getItem("phid_pc").getValue() },
				function (res) {
					console.log('项目信息获取', res);
					const datas = JSON.parse(res.data)[0].extendObjects;
					console.log(datas, "11111111111");
					//帮助字段赋值
					$NG.updateState((updater) => {
						updater.data.p_form_procurement_spare_m.setProps({
							// u_supply_att: datas.u_supply_att, //计划完工日期
							// u_supply_name: datas.u_supply_name, //计划竣工日期
							u_pc_no: datas.pc_no, //项目编码
							u_budget_org_name: datas.budget_org_name,
							u_budget_org_no: datas.budget_org_no,
							u_dept: {
								value: datas.dept_phid,
								label: datas.dept_name,
							},
							u_division: {
								//事业部or组织
								value: datas.division_phid,
								label: datas.division_name,
							},

							u_regional_center: {
								//区域中心
								value: datas.regional_center_phid,
								label: datas.regional_center_name,
							},
							u_product_line: {
								//产品线
								value: datas.midwife_phid,
								label: datas.midwife_name,
							},
							phid_org: {
								value: datas.org_phid,
								label: datas.org_name,
							},
							u_budget_org_no: datas.budget_org_no,
							u_budget_org_name: datas.budget_org_name
						});
					});
				}
			);
		}
		$NG.execServer(
			"projectSjbm",
			{ phid: `${mstform.getItem("phid_pc").getValue()}` },
			function (res) {
				try {
					const datas = JSON.parse(res.data)[0].extendObjects;
					//商机号
					mstform.getItem("u_sjh").setValue(datas.user_sjbm);
					//商机编码
					mstform.getItem("u_sjmc").setValue(datas.user_sjmc);
				} catch (error) { }
			}
		);
	}

	useValuesChange(({ args }) => {
		console.log(args, "u_budget_org");
	}, "p_form_procurement_spare_m.u_budget_org");
	/**
	 *@function:计算逻辑
	 */
	useUpdateRow(({ args }) => {
		console.log(args[0], "分包明细表 计算");
		let row = args[0];
		if (
			args[0].u_cost_pc_EXName &&
			mstform.getItem("phid_pc").getValue() &&
			mstform.getItem("u_budget_org").getValue() &&
			mstform.getItem("phid_fcur").getValue()
		) {
			const _maps = {
				billType: "WKSD",
				phid_pc: mstform.getItem("phid_pc").getValue(),
				bill_dt: mstform.getItem("bill_dt").getValue(),
				detail: [
					{
						u_entity: "WKSSXMZZ",
						u_account: args[0].u_cost_pc_EXName,
						phid_fcur: mstform.getItem("phid_fcur").getValue(),
					},
				],
			};
			// reqAmt(_maps);
		}
		computedV2(row);
		// 更新和刷新表格
		grid1.refreshView();
	}, "p_form_procurement_spare_d");
	cntDFilter()
	function cntDFilter() {
		$NG.updateUI(updater => updater.editGrid.p_form_procurement_spare_d.u_budget_account.setProps((p) => {
			return {
				...p, editor: {
					...p.editor,
					clientSqlFilter: { phid: '8570000000000393' },
				}
			};
		}));
		$NG.updateUI(updater => updater.editGrid.p_form_procurement_spare_d.u_cost_pc.setProps((p) => {
			return {
				...p, editor: {
					...p.editor,
					clientSqlFilter: { phid: '8570000000000393' },
				}
			};
		}));
	}
	useClick(async ({ args }) => {
		setTimeout(() => {
			const arr = grid1.getRows()
			arr.forEach(item => {
				if (!item.u_balance) {
					reqAmt(item.u_budget_account, (_data) => {
						item.u_balance = _data.balance
						grid1.refreshView()
					})
				}
			})
			$NG.message("正在查询余额，请耐心等待~")
		}, 200)
	}, "addrow")
	useUpdateRows(({ args }) => {
		initUserType(args[0])
		computedV3(args[0])
		
		let rows = args[0];
		let total = 0;

		rows.forEach((item) => {
			//默认剩余量
			item.u_syl = item.u_qty

			if (item.u_balance == undefined || item.u_balance == NaN || item.u_balance == null) {
				// console.log({ ...item }, 'ceshi ');
				setTimeout(() => {
					reqAmt(item.u_budget_account, (data) => {
						item.u_balance = data.balance
						grid1.refreshView()
					})
				}, 200)
			}
			total += item.u_amt_vat || 0; // 确保值存在且为数字
			item.u_budget_account = 8570000000000393
			item.u_budget_account_EXName = '服务费_维修材料耗用'
			item.u_cost_pc = 8570000000000393
			item.u_cost_pc_EXName = '服务费_维修材料耗用'
			if (item.itemid) {
				$NG.execServer("searchMasterP", { phid: item.itemid }, function (res) {
					const datas = JSON.parse(res.data)[0].extendObjects;
					// console.log(datas, "xxxxxxxx");
					item.itemno = datas.itemno;
					item.spec = datas.spec;
					item.msunit = datas.msunit_phid;
					item.msunit_EXName = datas.msunit_name; //单位
					// item.u_item_sub = datas.res_bs_phid; //单位
					// item.u_item_sub_EXName = datas.res_bs_name; //单位
					grid1.refreshView();
				});
			}
		});
		grid1.refreshView()
		mstform.getItem("u_amt_vat").setValue(total);
		console.log("Total u_amt_vat:", total);

		// 更新和刷新表格
		// 带物料相信息;
	}, "p_form_procurement_spare_d");
	// TODO 单行更改触发请求，赋值到金额
	useDataIndexChange(async ({ args }) => {
		console.log(`费用项目监听测试`, args);
		if (args[0].u_budget_account_EXName) {
			await reqAmt(args[0].u_budget_account, (_data) => {

				args[0].u_balance = _data.balance;
				grid1.refreshView();
			});

		}
	}, "u_budget_account");
	// useDataIndexChange(async ({ args }) => {
	// 	if (args[0].u_budget_account) {
	// 		const _maps = {
	// 			billType: "WKSD",
	// 			phid_pc: mstform.getItem("phid_pc").getValue(),
	// 			bill_dt: mstform.getItem("bill_dt").getValue(),
	// 			detail: [
	// 				{
	// 					u_entity: mstform.getItem("u_budget_org").getValue(),
	// 					u_account: args[0].u_budget_account,
	// 					phid_fcur: mstform.getItem("phid_fcur").getValue(),
	// 				},
	// 			],
	// 		};
	// 		const resBody = await reqAmt(_maps);
	// 		const _data = resBody.data[0];
	// 		args[0].u_balance = _data.balance;
	// 		grid1.refreshView();
	// 	}
	// }, "u_budget_account");

	function computedV2(rowItem) {
		const record = rowItem;

		// 提供默认值并确保为数字类型，防止字符串影响计算
		const u_qty = Number(record.u_qty) || 0; // 数量，默认为 0
		const u_vat_prc = Number(record.u_vat_prc) || 0; // 含税单价，默认为 0
		const u_tax_rate = Number(record.u_tax_rate) || 0; // 税率，默认为 0

		// 计算不含税单价
		const u_prc = u_vat_prc / (1 + u_tax_rate);

		// 计算字段值
		const u_amt_vat = u_qty * u_vat_prc; // 价税合计
		const u_amt = u_qty * u_prc; // 不含税金额
		const u_tax_amt = u_amt_vat - u_amt; // 税额
		const u_amt_vat_fc = u_amt_vat; // 价税合计（与 u_amt_vat 相同）

		// 更新 record 对象
		Object.assign(record, {
			u_prc,
			u_amt_vat,
			u_amt,
			u_tax_amt,
			u_amt_vat_fc,
		});
	}
	function computedV3(rowItems) {
		// 遍历数组中的每个对象
		rowItems.forEach(record => {
			// 提供默认值并确保为数字类型，防止字符串影响计算
			const u_qty = Number(record.u_qty) || 0;     // 数量，默认为 0
			const u_vat_prc = Number(record.u_vat_prc) || 0; // 含税单价，默认为 0
			const u_tax_rate = Number(record.u_tax_rate) || 0; // 税率，默认为 0
	
			// 计算不含税单价
			const u_prc = u_vat_prc / (1 + u_tax_rate);
	
			// 计算字段值
			const u_amt_vat = u_qty * u_vat_prc;        // 价税合计
			const u_amt = u_qty * u_prc;                // 不含税金额
			const u_tax_amt = u_amt_vat - u_amt;         // 税额
			const u_amt_vat_fc = u_amt_vat;              // 价税合计（与 u_amt_vat 相同）
	
			// 更新当前对象
			Object.assign(record, {
				u_prc,
				u_amt_vat,
				u_amt,
				u_tax_amt,
				u_amt_vat_fc,
			});
		});
	}
	// 查询余额请求体
	async function reqAmt(km, fun) {
		if (!mstform.getItem("phid_pc").getValue()) return
		const _maps = {
			billType: "SD-0001",
			phid_pc: mstform.getItem("phid_pc").getValue(),
			bill_dt: mstform.getItem("bill_dt").getValue(),
			detail: [
				{
					u_entity: "WKSSXMZZ",
					u_account: km,
					phid_fcur: mstform.getItem("phid_fcur").getValue(),
				},
			],
		};
		console.log('请求参数检查', _maps);
		const resBody = await $NG.request.post({
			url: "http://nginx.clouddev.hisense.com/sd/sdToFi/fiIntegration/fiCheckBalance",
			// url: "https://inner-apisix.hisense.com/hisense/sd/Fi/sdToFi/fiIntegration/fiCheckBalance?user_key=pxgy9hyt9udfgfcsbzizykw0xfqi6uk6 ",
			data: JSON.stringify(_maps),
			header: {
				"Content-Type": "application/json",
			},
		});
		console.log(`响应信息`, resBody);
		if (!resBody.IsOk) {
			$NG.message(resBody.Message)
		}
		const _data = resBody.data[0];
		fun(_data)
	}
	useBeforeClick(async function ({ args }) {
		(function () { })();

		const _arr = grid1.getRows();
		const _index = [];
		let lock = true
		_arr.forEach((item, index) => {
			if ((Number(item.u_balance) || 0) < (Number(item.u_amt_vat) || 0)) {
				_index.push(index + 1);
			}
			if (item.u_balance == undefined || item.u_balance == null) {
				lock = false
			}
		});
		console.log(`保存为`, lock);
		if (!lock) {
			$NG.alert(`有明细余额为空！`)
			return false
		}
		if (_index.length !== 0) {
			$NG.alert(`明细中第 ${_index.join("、")} 行中，价税合计超出余额！！`);
			return false;
		}
		return true;
	}, "save");

	useClick((prop) => {
		setTimeout(() => {
			console.log("")
			$NG.execServer(
				"getPhidKey",
				{ phidkey: mstform.getItem("u_phidkey").getValue() },
				(res) => {
					console.log(res);
					
					if (res.count == 0) return
					mstform.getItem("u_phidkey").getValue()
					console.log(`响应信息datasssss??`);
					const datas = JSON.parse(res.data)[0].extendObjects;
					console.log("datas", datas);
					async function pushPhid() {
						const resBody = await $NG.request.post({
							url: "http://nginx.clouddev.hisense.com/sd/sdToFi/fiIntegration/pushBudgetPreoccupation",
							// url: "https://inner-apisix.hisense.com/hisense/sd/Fi/sdToFi/fiIntegration/pushBudgetPreoccupation?user_key=pxgy9hyt9udfgfcsbzizykw0xfqi6uk6",
							data: JSON.stringify({ phid: datas.phid }),
							header: {
								"Content-Type": "application/json",
							},
						});
						console.log(`响应信息1111`, resBody);
						return resBody;
					}
					pushPhid();
				}
			);
		}, 2000);
	}, "save");
    useBeforeClick(()=>{
        if(page.oType == 'add'){
            $NG.alert("请先保存！")
            return false
        }
        // const flag = mstform.getItem("u_fi_flag").getValue()
        // const msg = mstform.getItem("u_fi_msg").getValue()
        // switch(flag){
        //     case '2':
        //         $NG.alert("预占终占推送失败！"+msg)
        //         return false
        //     case null:
        //         $NG.alert("预占终占推送中，请稍后重试！")
        //         return false
        //     default:
        //         return true
        // }
    },'check')
});
function initUserType(_data) {
	_data.forEach((item) => {
		item.u_dj_status = '1'
	})
	// grid1.refreshView();
}
function generateKey() {
	// 使用 Date.now() 获取当前时间戳
	let timestamp = Date.now();
	// 使用 Math.random() 生成一个随机数
	let random = Math.random();
	// 将时间戳和随机数组合，并转换为字符串
	let key = timestamp.toString() + random.toString();
	return key;
}
